---
--类名: PopupUI.lua
--创建日期: 2015-9-19
--创建人: 陈小虎
--功能描述: 弹出ui管理
--修改内容:
--修改日期:
--修改人:
--修改备注:
--

local PopupUI = class("PopupUI",function()
    return display.newNode()
end)

PopupUI.mInstance = nil

-- function PopupUI.getInstance()
--     if PopupUI.mInstance == nil then
--         PopupUI.mInstance = PopupUI.new()
--     end
--     return PopupUI.mInstance
-- end

function PopupUI:ctor()
	self._uiKeys = {}
end

function PopupUI:openTouchMask()
    self:addTouchMask()
end

function PopupUI:closeTouchMask()
    self:removeTouchListener()
end

function PopupUI:addTouchMask()
    self:removeTouchListener()
    self._touchMaskListener = cc.EventListenerTouchOneByOne:create()
    self._touchMaskListener:setSwallowTouches(true)
    self._touchMaskListener:registerScriptHandler(function(touch, event)
        return true
    end, cc.Handler.EVENT_TOUCH_BEGAN)

    self._touchMaskListener:registerScriptHandler(function(touch, event)
        end, cc.Handler.EVENT_TOUCH_ENDED)
    self:getEventDispatcher():addEventListenerWithSceneGraphPriority(self._touchMaskListener, self)
end

function PopupUI:removeTouchListener()
    if self._touchMaskListener then
        self:getEventDispatcher():removeEventListener(self._touchMaskListener)
        self._touchMaskListener = nil
    end
end

function PopupUI:isHaveUI()
    return table.nums(self._uiKeys) > 0
end

function PopupUI:isCreateUi(uiKey)
    return self:getChildByName(uiKey)
end

function PopupUI:getUIByKey(uiKey)
    return self:getChildByName(uiKey)
end

function PopupUI:addUI(uiKey,uiNode,notDelete)
    if uiNode then
        self:addChild(uiNode)
    end
    if uiKey then
        uiNode:setName(uiKey)
    end

	if uiKey and not notDelete then
        self._uiKeys[uiKey] = uiKey
    end
end

function PopupUI:removeUI(uiKey,uiNode)
    if uiKey then
        self._uiKeys[uiKey] = nil
    end
    if uiNode then
        self:removeChild(uiNode)

        self:checkEmpty()
    end
end

function PopupUI:removeUIByKey(uiKey)
    if not uiKey then return end
    if self:isCreateUi(uiKey) then
        self:removeChildByName(uiKey)

        self._uiKeys[uiKey] = nil
        self:checkEmpty()
    end
end

-- 设置清空回调
function PopupUI:setEmptyCB(cb)
    self._emptyCB = cb
end

-- 检查是否有子ui
function PopupUI:checkEmpty()
    if not self:isHaveUI() then
        executeFunc(self._emptyCB)
    end
end

function PopupUI:removeAllUI()
    -- self:removeAllChildren()
    local isHaveUI = self:isHaveUI()
    for k,uiKey in pairs(self._uiKeys) do
        self:removeChildByName(uiKey)
    end
    self._uiKeys = {}

    if isHaveUI then
        self:checkEmpty()
    end
end

return PopupUI
